// 全局请求路径，也就是后端的请求基准路径
// import {baseApi} from "@/config.js";
const baseApi = "/zhaocaibaoBackApi/"; // 服务器地址
// const baseApi = "http://pukei.cn/zhaocaibaoBackApi/"; // 服务器地址

// 同时发送异步代码的次数，防止一次点击中有多次请求，用于处理
let ajaxTimes = 0;
const defaultHeader = {
	'content-type': 'application/json;charset=UTF-8',
	withCredentials: true,
	crossDomain: true
}

// 封装请求方法，并向外暴露该方法
const myHttp = (options) => {
	// 解构请求头参数
	let header = {};
	if (options.header) {
		header = {
			...defaultHeader,
			...options.header
		};
	}
	// console.log(options.header);
	const isToken = (options.header || {}).isToken === false;
	let token = uni.getStorageSync('token')
	const userInfo = uni.getStorageSync("userInfo")
	if (token && !isToken) {
	  header['Authorization'] = token // 让每个请求携带自定义token 请根据实际情况自行修改
	}
	// TODO  测试
	// header['Authorization'] =
	// 	'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2NDkyOTg0ODAsImlhdCI6MTY0OTIxMjA4MCwidXNlcl9pZCI6Mjk0OH0.pKVHc7x7ikT8fHx-PUvNDI730nb91Ebh7vmIV8UxuOE'
	// console.log(isToken, userInfo)
	console.log(isToken)
	if (!isToken && !userInfo) {
		setTimeout(() => {
			let loginPath = "/pages/login/login";
			uni.reLaunch({
				url: loginPath,
			})
		}, 1000)
	}
	if (ajaxTimes == 0 && !options.hideLoad) {
		// NProgress.start()
		uni.showLoading({
			title: "加载中",
			mask: true,
		});
	}
	ajaxTimes++;
	// 显示加载中 效果
	// console.log("ajaxTimes------",ajaxTimes)

	return new Promise((resolve, reject) => {
		console.log(baseApi + options.url)
		let url = baseApi + options.url
		if (options.url.includes("http")) {
			url = options.url
		}
		uni.request({
			url: url,
			method: options.method || 'get',
			data: options.data || options.params || {},
			header,
			success: (res) => {
				uni.stopPullDownRefresh()
				// console.log(res.data)
				// console.log("routes==",routePath);
				// console.log(res.data)
				// uni.showModal({
				// 	title: res.code,
				// 	content: JSON.stringify(res.data.msg)
				// })
				// uni.showModal({
				// 	title: res.code,
				// 	content: JSON.stringify(baseApi + options.url)
				// })
				console.log("resres", res)
				resolve(res.data)
				if (res.data.code == 0 || res.data.code == 200) {
					resolve(res.data)
				} else {
					switch (res.data.code) {
						case 401:
							uni.showToast({
								title: '登录失效，请重新登录',
								icon: 'none',
								duration: 2000
							});

							uni.removeStorageSync('token');
							let routes = getCurrentPages();
							let routePath = routes.length > 0 && routes[0].route;
							let loginPath = "/pages/index/index";

							if (routePath != loginPath) {
								uni.reLaunch({
									url: loginPath,
								})
							}

							break
						case 403:
							console.log("进入了403")
							uni.removeStorageSync("token")
							uni.showToast({
								title: res && res.data.msg || '拒绝访问',
								icon: 'none',
								duration: 4000
							});
							break
						case 404:
							uni.showToast({
								title: res && res.data.msg || '很抱歉，资源未找到!',
								icon: 'none',
								duration: 4000
							});
							break
						case 500:
							uni.showToast({
								title: res && res.data.msg || '服务器错误',
								icon: 'none',
								duration: 2000
							});
							break;
						case 502:
							uni.showToast({
								title: res && res.data.msg || '服务器异常',
								icon: 'none',
								duration: 2000
							});
							break;
						case 100:
							uni.showToast({
								title: res && res.data.msg || '服务器异常',
								icon: 'none',
								duration: 2000
							});
							uni.setStorageSync("token", res.data.results.Authorization)
							let userInfo = uni.getStorageSync("userInfo")
							userInfo = {...userInfo, ...{yh_username: res.data.results.yh_username}}
							uni.setStorageSync("userInfo", userInfo)
							setTimeout(() => {
								uni.switchTab({
									// url: "/pages/login/registerPhone?yh_username=" + res.data.results.yh_username
									url: "/pages/index/index"
								})
							}, 2000)
							break;
						default:
						ajaxTimes++
							uni.showToast({
								title: res && res.data.msg || '操作成功',
								icon: 'none'
							});
							setTimeout(() => {
								ajaxTimes--
							}, 2000)
					}
					reject(res.data)
				}
			},
			fail: (error) => {
				setTimeout(function() {
					console.log(error)
					// console.log(error)
					uni.showToast({
						title: error && error.msg || '网络繁忙，请稍后再试',
						icon: 'none',
						duration: 2000
					});
				}, 100)
				reject(error)
			},
			// 完成之后关闭加载效果
			complete: () => {
				ajaxTimes--;
				// console.log("ajaxTimes======>>",ajaxTimes)
				if (ajaxTimes === 0 && !options.hideLoad) {
					//  关闭正在等待的图标
					uni.hideLoading();
				}
			}
		})
	})
}
export default myHttp;

/**
 * 上传文件
 * @param {Object} tempFilePath uni文件路径
 */
export function saveFile(tempFilePath) {
	console.log(tempFilePath)
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: baseApi + "common/upload",
			header: {
				'Authorization': 'Bearer ' + uni.getStorageSync('token'),
			},
			filePath: tempFilePath,
			name: 'file',
			success: (uploadFileRes) => {
				if (uploadFileRes.statusCode == 200) {
					let resData = JSON.parse(uploadFileRes.data)
					resolve(resData)
				} else {
					reject(err)
				}
			},
			fail: (err) => {
				reject(err)
			}
		});
	})
};
